package tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description: 513. 找树左下角的值
 * User: Li_yizYa
 * Date: 2025/6/3
 * Time: 21:59
 */
public class Solution20 {
    private int Deep = -1;
    private int ret = 0;
    public int findBottomLeftValue(TreeNode root) {
        if (root == null) {
            return Integer.MIN_VALUE;
        }
        ret = root.val;
        findLeftValue(root, 0);
        return ret;
    }
    private void findLeftValue(TreeNode root, int deep) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null && deep > Deep) {
            ret = root.val;
            Deep = deep;
        }
        if (root.left != null) {
            findLeftValue(root.left, deep + 1);
        }
        if (root.right != null) {
            findLeftValue(root.right, deep + 1);
        }
    }
    public int findBottomLeftValue1(TreeNode root) {
        if (root == null) {
            return Integer.MIN_VALUE;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ret = 0;
        while (!queue.isEmpty()) {
            int len = queue.size();
            int flag = 0;
            while (len > 0) {
                TreeNode node = queue.poll();
                if (flag == 0) {
                    ret = node.val;
                    flag = 1;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                len--;
            }
        }
        return ret;
    }
}
